<template>
  <div class="app-container">
    <el-card id="dlls_card" class="box-card" style="text-align: center;">
      <div style="width: 98%; margin: 0 auto">
        <div
          style="
          margin: 10px 0;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 10px;
        "
        >
          <el-upload
            class="upload-demo"
            list-type="text"
            accept=".xls,.xlsx"
            :action="UploadUrl()"
            :limit="1"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :file-list="fileList"
          ><el-button type="primary">添加</el-button>
          </el-upload>
          <el-button type="danger" @click="delUser">删除</el-button>
          <el-button type="primary" @click="pluginDownload">下载模板</el-button>

        </div>

        <div>
          <drag-head
            ref="dragHeadRef"
            :show-all-filter-condition="showAllFilterCondition"
            :store-names="storeName"
            :head-columns="tableHead"
            :data="backendUserList"
            :loading="loading"
            @handleSelectionChange="handleSelectionChange"
            @sort_change="sort_change"
            @fresh="fresh"
          />
          <!--<div class="" style="margin-top: 10px; float: right;margin-bottom: 10px;">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[10, 15, 20, 25, 50, 100, 200]"
              :current-page.sync="page"
              :page-size="page_size"
              layout="sizes, prev, pager, next, total"
              :total="total"
            >
            </el-pagination>
          </div>-->
        </div>
      </div>
    </el-card>

    <keep-alive>
      <router-view />
    </keep-alive>
  </div>
</template>

<script>
import {
  getReplyTemplateUpload,
  getReplyTemplateList,
  getReplyTemplateDisable
} from '../../api'
import DragHead from './dragHead.vue'
import NoticeBar from './noticeBar.vue'
import JsonExcel from 'vue-json-excel'
import qs from 'qs'
export default {
  components: { DragHead, DownloadExcel: JsonExcel, NoticeBar },
  data() {
    return {
      fileList: [],
      visible: false,
      page_size: 50,
      page: 1,
      total: 0,
      backendUserList: [],
      loading: false,
      tableHead: [
        {
          label: '模版ID',
          prop: 'ID',
          width: 90,
          sortable: false,
          show: true
        },
        {
          label: '备注',
          prop: 'note',
          width: 100,
          sortable: false,
          show: true
        },
        {
          label: '模板地址',
          prop: 'url',
          width: 200,
          sortable: false,
          show: true
        }

      ],
      storeName: 'commentTemplate',
      showAllFilterCondition: false,
      selectadUserIdsList: []
    }
  },
  watch: {
  },
  created() {
    const url = window.location.href
    let arr = localStorage.getItem(this.storeName)
    if (arr != null && arr.length != this.tableHead.length) {
      localStorage.removeItem(this.storeName)
      arr = localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
    }
    if (arr) {
      const isClearLocal = JSON.parse(arr).find(
        (item) =>
          item.prop === 'advertiser_id' && (!item.show || item.show === false)
      )
      if (isClearLocal) {
        const newArr = []
        JSON.parse(arr).forEach((item) => {
          if (item !== null) {
            if (!item['show']) {
              item['show'] = true
            }
            newArr.push(item)
          }
        })
        localStorage.setItem(this.storeName, JSON.stringify(newArr))
      }
    } else {
      localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
    }

    var role = Number(window.localStorage.getItem('role'))
    const date = new Date()
    const year = date.getFullYear() // 获取完整的年份(4位)
    let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
    let strDate = date.getDate() // 获取当前日(1-31)
    if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
    if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
    this.value1 = [
      `${year}-${month}-${strDate}`,
      `${year}-${month}-${strDate}`
    ]
    this.getList()
  },
  methods: {
    pluginDownload() {
      const url = 'https://bdw-public-1259268558.cos.ap-nanjing.myqcloud.com/auto_comment_template.xlsx'
      this.axios.get(url, {
        responseType: 'blob'
      }).then((res) => {
        // console.log(res)
        const link = document.createElement('a')
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', 'auto_comment_template.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })

      // const a = document.createElement('a');
      // a.href = url;
      // a.download = "auto_comment_template.xlsx";
      // a.style.display = 'none';
      // document.body.appendChild(a);
      // a.click() ;
      // document.body.removeChild(a)
    },
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.selectadUserIdsList = val.map((item) => item.ID)
      } else {
        this.selectadUserIdsList = []
      }
    },
    async delUser() {
      if (this.selectadUserIdsList.length === 0) {
        this.$message.error('请选择删除的数据')
        return
      }
      // let { selectadUserIdsList } = this;
      const res = await getReplyTemplateDisable({
        ids: [null, null]
      }).catch((e) => e)
      if (res.code === 0) {
        this.$message.success('删除成功')
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    },
    beforeUpload(file) {
      // console.log(file, '文件')
      this.files = file
      const isLt5M = file.size / 1024 / 1024 < 3
      if (!isLt5M) {
        this.$message.warning('上传大小不能超过 3MB!')
        return
      }
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      // 获取到文件的大小
      const size = file.size / 1024 / 1024
      // 判断文件类型
      if (extension !== 'xlsx' && extension !== 'xls') {
        this.$message.warning('只能上传后缀是.xlsx或者.xls的文件')
        return
      }
      setTimeout(() => {
        this.handleUploadFile()
      }, 500)
    },
    async handleUploadFile() {
      const dataFile = new FormData()
      // console.log(this.fileList[0])
      dataFile.append('token', localStorage.getItem('token'))
      dataFile.append('file', this.fileList[0])
      this.axios.post('/v1/file/reply_template/upload', dataFile, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        if (res.data.code === 0) {
          this.getList()
        } else {
          this.fileList = []
          this.$message.error(res.data.msg)
        }
      })
    },
    handleChange(file, fileList) {
      this.fileList.push(file.raw)
    },
    // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
    UploadUrl() {
      return ''
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    openCustomModal() {
      this.$refs.dragHeadRef.openCustomModal()
    },
    fresh() {
      this.backendUserList = []
      this.getList()
    },
    async getList(obj, isAll) {
      // console .log('obj', obj)
      const {
        page_size,
        page
      } = this
      if (!isAll) {
        this.loading = true
      }
      const res = await getReplyTemplateList({
        page_size: isAll ? 9999 : page_size,
        page
      }).catch((e) => e)
      this.$refs.dragHeadRef.renderTable()
      this.loading = false
      if (res.code === 0) {
        this.selectadUserIdsList = []
        this.backendUserList = res.data
      } else {
        this.backendUserList = []
        this.$message.error(res.msg)
      }
    },
    sort_change(column) {
      this.getList()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val

      this.getList()
    }
  }
}
</script>

<style lang="scss">
  html,
  body {
    height: 100%;
  }

  .scroll::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 10px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 12px;
  }

  .scroll::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    -webkit-box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);
    background: #fff;
  }

  .scroll::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.8);
    border-radius: 10px;
    background: #888;
  }

  .dataPicker {
    white-space: pre;
    margin: 0 10px 0 30px;
  }

  .inputM {
    margin: 0 5px;
    width: 150px;
  }

  .operBtn {
    text-align: center;
  }

  .export-btn {
    display: inline;
    margin-left: 10px;
  }

  .pddTable {
    .el-table .cell {
      // white-space: nowrap;
      // overflow: hidden;
      // text-overflow: ellipsis;
    }
  }

  .el-range-editor--small .el-range-separator {
    margin: 0 10px !important;
  }
</style>
